package cn.cq.admin.service.impl;

import cn.cq.admin.service.UploadService;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadFileStreamRequest;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadFileStreamResponse;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoRequest;
import com.aliyuncs.vod.model.v20170321.GetPlayInfoResponse;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
@ConfigurationProperties(prefix = "aliyun.oss")
@Slf4j
@Setter
public class UploadServiceImpl implements UploadService, InitializingBean {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String imgPath;
    private String videoPath;
    private String regionId;

    public static  String REGIONID;
    public static String ACCESSKEYID;
    private static String ACCESSKEYSECRET;

    public static DefaultAcsClient initVodClient() {
        DefaultProfile profile = DefaultProfile.getProfile(REGIONID, ACCESSKEYID, ACCESSKEYSECRET);
        return new DefaultAcsClient(profile);
    }

    @Override
    public String uploadFile(MultipartFile multipartFile) {
        String uuid = UUID.randomUUID(false).toString(true);
        String originalFilename = multipartFile.getOriginalFilename();
        int lastIndexOf = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(lastIndexOf, originalFilename.length());
        String objectName = imgPath + uuid+suffix;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = multipartFile.getInputStream();
            PutObjectResult result = ossClient.putObject(bucketName, objectName, inputStream);

            String url = endpoint
                    .replace("https://", "https://ydj-online-study-system" + ".")
                    + "/" + objectName;
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (ObjectUtil.isNotNull(ossClient)) {
                ossClient.shutdown();
            }
        }
        return null;
    }

    @Override
    public String uploadVideo(MultipartFile multipartFile) {
        String originalFilename = multipartFile.getOriginalFilename();
        String title = originalFilename;
        UploadStreamRequest request = null;
        try {
            request = new UploadStreamRequest(accessKeyId, accessKeySecret, title, originalFilename,multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        UploadVideoImpl uploadVideo = new UploadVideoImpl();
        UploadStreamResponse resp = uploadVideo.uploadStream(request);
        String videoId = resp.getVideoId();
        log.info("videoId",videoId);
        return videoId;
    }


    @Override
    public String getVideoAddress(String videoId) {
        try {
            return getPlayAddress(videoId);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getPlayAddress(String videoId) throws ClientException {
        DefaultAcsClient client = UploadServiceImpl.initVodClient();
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        GetPlayInfoResponse response = new GetPlayInfoResponse();
        request.setVideoId(videoId);
        response = client.getAcsResponse(request);
        List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
        playInfoList.forEach((p) -> {
            log.info("playInfo:{}", p.getPlayURL() + "\n");
        });
        return playInfoList.get(0).getPlayURL();
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        REGIONID = regionId;
        ACCESSKEYID = accessKeyId;
        ACCESSKEYSECRET = accessKeySecret;
    }
}
